package com.oa.web;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.oa.bean.UserInfo;
import com.oa.biz.impl.UserInfoServiceImpl;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    
	@SuppressWarnings("unused")
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		
		String uName=request.getParameter("userName");
		String pwd=request.getParameter("pwd");
//		System.out.println(uName+"--"+pwd);
		
		UserInfo user=new UserInfoServiceImpl().login(new UserInfo(uName,pwd));
		System.out.println("登录用户名==>"+user.getUserName());
//		System.out.println("登录id==>"+user.getUserName());
		
		if (user!=null) {
			HttpSession session=request.getSession();		
			if (session.getAttribute("id")!=null||session.getAttribute("roleId")!=null) {
				session.removeAttribute("id");
				session.removeAttribute("roleId");
//				System.out.println("移除后获取的id是:==>"+session.getAttribute("id"));
			}
			session.setAttribute("id", user.getUserId());
			session.setAttribute("roleId", user.getRoleId());
			System.out.println("获取的id是:==>"+session.getAttribute("id"));
			System.out.println("获取的roleId是:==>"+session.getAttribute("roleId"));

			if (user.getUserId()==1) {
				response.sendRedirect("jsp/plan/manage_plan_note.jsp");
			}else {
				response.sendRedirect("jsp/sign/manage_sign.jsp");
			}		
		}else {
			response.getWriter().write(""
					+ "<script>"
					+ "alert('用户名或密码错误,请重新登录');"
					+ "location.href='login.jsp';"
					+ "</script>");
		}				
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
